<template>
  <div class="container">
    <h1>留言板</h1>
    <form @submit.prevent="addMessage">
      <input v-model="author" placeholder="你的名字" required />
      <input v-model="content" placeholder="留言内容" required />
      <button type="submit">提交</button>
    </form>
    <ul>
      <li v-for="msg in messages" :key="msg.id">
        <strong>{{ msg.author }}:</strong> {{ msg.content }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const messages = ref([])
const author = ref('')
const content = ref('')

const fetchMessages = async () => {
  try {
    const res = await axios.get('/api/messages')
    messages.value = res.data
  } catch (err) {
    console.error(err)
  }
}

const addMessage = async () => {
  if (!author.value || !content.value) return
  try {
    await axios.post('/api/messages', {
      author: author.value,
      content: content.value
    })
    author.value = ''
    content.value = ''
    fetchMessages()
  } catch (err) {
    console.error(err)
  }
}

onMounted(fetchMessages)
</script>

<style>
.container {
  max-width: 500px;
  margin: 40px auto;
  font-family: Arial, sans-serif;
}

form {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}

input {
  flex: 1;
  padding: 8px;
}

button {
  padding: 8px 12px;
}
</style>
